const axios = require('axios')
const forge = require('node-forge')
const CryptoJS = require('crypto-js')
const FormData = require('form-data')
const { getEnvString } = require('./env')


const privateKey = getEnvString('AIQIAN_PRIVATE_KEY')

const appId = getEnvString('AIQIAN_APP_ID')

// 签名
function signature(jsonString, timestamp) {
  const signString = jsonString + CryptoJS.MD5(jsonString) + appId + timestamp
  const privKey = forge.pki.privateKeyFromPem(privateKey)
  const md = forge.md.sha1.create()
  md.update(signString, 'utf8')
  return forge.util.encode64(privKey.sign(md))
}

// json排序
function sortJSON(obj) {
  if (Array.isArray(obj)) {
    if (obj.length !== 0 && typeof (obj[0] === 'object')) {
      for (let i = 0; i < obj.length; i++) {
        obj[i] = sortJSON(obj[i])
      }
    }
    return obj
  } else {
    for (const key of Object.keys(obj)) {
      const value = obj[key]
      if (Array.isArray(value)) {
        if (value.length !== 0 && typeof value[0] === 'object') {
          for (let i = 0; i < value.length; i++) {
            value[i] = sortJSON(value[i])
          }
        }
      } else if (typeof value === 'object') {
        obj[key] = sortJSON(value)
      }
    }

    return Object.fromEntries(Object.entries(obj).sort((o1, o2) => o1[0].localeCompare(o2[0])))
  }
}

// 发送请求的函数
async function sendRequest(bizData, url) {
  const jsonString = JSON.stringify(sortJSON(bizData))
  const timestamp = Date.now() + 1000 * 60 * 10
  const sign = signature(jsonString, timestamp)

  const formData = new FormData()
  formData.append('appId', encodeURIComponent(appId))
  formData.append('timestamp', encodeURIComponent(timestamp))
  formData.append('bizData', jsonString)

  const config = {
    method: 'post',
    url: `${getEnvString('AIQIAN_API_URL')}${url}`,
    headers: {
      'Content-Type': 'multipart/form-data',
      sign,
      timestamp: timestamp
    },
    data: formData
  }

  try {
    const response = await axios(config)
    return response.data
  } catch (error) {
    console.error('Error sending request:', error)
    throw error
  }
}

module.exports = {
  sendRequest
}
